package com.hlk.article.controller;

import com.hlk.article.service.ArticlePortalService;
import com.hlk.article.utils.RestTemplateUtils;
import com.hlk.constant.Constant;
import com.hlk.controller.article.ArticlePortalControllerApi;
import com.hlk.feign.UserFeignClient;
import com.hlk.pojo.Article;
import com.hlk.pojo.vo.AppUserVO;
import com.hlk.pojo.vo.ArticleDetailVO;
import com.hlk.pojo.vo.IndexArticleVO;
import com.hlk.result.Result;
import com.hlk.utils.ConvertUtils;
import com.hlk.utils.IPUtil;
import com.hlk.utils.JsonUtils;
import com.hlk.utils.PageResult;
import com.hlk.utils.redis.RedisKeys;
import com.hlk.utils.redis.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author hlk
 * @version 1.0
 * @date 2021-01-07 14:46
 */
@RestController
public class ArticlePortalController implements ArticlePortalControllerApi {
    @Autowired
    private ArticlePortalService articlePortalService;
    @Autowired
    private RestTemplateUtils restTemplateUtils;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public Result list(String keyword, Integer category, Integer page, Integer pageSize) {
        if (page == null) {
            page = Constant.PAGE;
        }
        if (pageSize == null) {
            pageSize = Constant.PAGESIZE;
        }
        PageResult pageResult = articlePortalService.selectArticleList(keyword, category, page, pageSize);

        rebuildArticle(pageResult);

        return Result.ok(pageResult);
    }

    @Override
    public Result readArticle(String articleId, HttpServletRequest request) {
        String ip = IPUtil.getRequestIp(request);
//        if (StringUtils.isBlank(redisUtils.get(RedisKeys.getArticleReadedKey(articleId, ip)))) {
        redisUtils.setnx(RedisKeys.getArticleReadedKey(articleId, ip), ip);
        redisUtils.increment(RedisKeys.getArticleReadCountsKey(articleId), 1);
//        }
        return Result.ok();
    }

    @Override
    public Result hotList() {
        return Result.ok(articlePortalService.queryHotList());
    }

    @Override
    public Result queryArticleListOfWriter(String writerId, Integer page, Integer pageSize) {
        if (page == null) {
            page = Constant.PAGE;
        }
        if (pageSize == null) {
            pageSize = Constant.PAGESIZE;
        }

        PageResult pageResult = articlePortalService.queryArticleListOfWriter(writerId, page, pageSize);
        rebuildArticle(pageResult);
        return Result.ok(pageResult);
    }

    @Override
    public Result queryGoodArticleListOfWriter(String writerId) {
        PageResult pageResult = articlePortalService.queryGoodArticleListOfWriter(writerId);
        return Result.ok(pageResult);
    }

    @Override
    public Integer readCounts(String articleId) {
        return getreadCounts(articleId);
    }

    /**
     * 获取用户阅读数
     *
     * @param articleId
     * @return
     */
    @NotNull
    private Integer getreadCounts(String articleId) {
        String countsStr = redisUtils.get(RedisKeys.getArticleReadCountsKey(articleId));
        if (StringUtils.isBlank(countsStr)) {
            countsStr = "0";
        }
        return Integer.valueOf(countsStr);
    }

    @Override
    public Result detail(String articleId) {
        ArticleDetailVO detailVO = articlePortalService.queryDetail(articleId);

        Set<String> idSet = new HashSet();
        idSet.add(detailVO.getPublishUserId());

//        List<AppUserVO> publisherList = restTemplateUtils.getPublisherList(idSet);

        Result bodyResult = userFeignClient.queryByIds(JsonUtils.objectToJson(idSet));
        List<AppUserVO> publisherList = null;
        if (bodyResult.getStatus() == 200) {
            String userJson = JsonUtils.objectToJson(bodyResult.getData());
            publisherList = JsonUtils.jsonToList(userJson, AppUserVO.class);
        }

        if (!publisherList.isEmpty()) {
            detailVO.setPublishUserName(publisherList.get(0).getNickname());
        }

        detailVO.setReadCounts(
                getreadCounts(articleId));

        return Result.ok(detailVO);
    }


    /**
     * 重新构建文章
     *
     * @param pageResult
     */
    private void rebuildArticle(PageResult pageResult) {
        // 获取用户信息
        List<Article> list = (List<Article>) pageResult.getRows();
        Set<String> idSet = new HashSet<>();
        List<String> idList = new ArrayList<>();
        list.forEach(item -> {
            // 构建用户ID
            idSet.add(item.getPublishUserId());
            // 构建文章用户ID
            idList.add(RedisKeys.getArticleReadCountsKey(item.getId()));
        });

        // 批量查询redis的数据
        List<String> articleReadCount = redisUtils.mget(idList);
        // 远程调用获取用户数据
//        List<AppUserVO> userVOList = restTemplateUtils.getPublisherList(idSet);

        Result bodyResult = userFeignClient.queryByIds(JsonUtils.objectToJson(idSet));
        List<AppUserVO> userVOList = null;
        if (bodyResult.getStatus() == 200) {
            String userJson = JsonUtils.objectToJson(bodyResult.getData());
            userVOList = JsonUtils.jsonToList(userJson, AppUserVO.class);
        }

        List<IndexArticleVO> indexArticleList = new ArrayList<>();
        // 拼接用户数据
        for (int i = 0; i < list.size(); i++) {
            IndexArticleVO indexArticleVO = ConvertUtils.sourceToTarget(list.get(i), IndexArticleVO.class);
            int readCounts = 0;
            String articleReadStr = articleReadCount.get(i);
            if (StringUtils.isNotBlank(articleReadStr)) {
                readCounts = Integer.valueOf(articleReadStr);
            }
            indexArticleVO.setReadCounts(readCounts);
            for (AppUserVO user : userVOList) {
                if (list.get(i).getPublishUserId().equalsIgnoreCase(user.getId())) {
                    indexArticleVO.setPublisherVO(user);
                }
            }
            indexArticleList.add(indexArticleVO);
        }

        pageResult.setRows(indexArticleList);
    }
}
